﻿using System.Text;
using System.Web.UI.WebControls;

namespace DatabaseAccess
{
    /// <summary>
    /// 用于给GridView，DropDownList等绑定数据的封装类
    /// </summary>
    public class BindDataHelper
    {
        private DBAccess m_DBA;

        /// <summary>
        /// 使用一个DBAccess对象作为参数的构造函数
        /// </summary>
        /// <param name="dba"></param>
        public BindDataHelper(DBAccess dba)
        {
            m_DBA = dba;
        }

        /// <summary>
        /// 将表table的内容绑定到control上
        /// </summary>
        /// <param name="control">要绑定数据的控件，可以是Gridview或者DropDownList等</param>
        /// <param name="table">要绑定的数据表名</param>
        /// <param name="cols">要绑定的列名。注意，如果对DropDownList绑定多列，必须指定其DataTextField和DataValueField属性</param>
        /// <param name="constrain">限制条件，不用包含where</param>
        public void BindData(DataBoundControl control, string table, string[] cols = null, string constrain = null)
        {
            StringBuilder sb = new StringBuilder("select ");
            if (cols != null)
            {
                foreach (string col in cols)
                {
                    sb.Append("\"").Append(col).Append("\"").Append(",");
                }
                sb.Remove(sb.Length - 1, 1);
                sb.Append(" ");

            }
            else
            {
                sb.Append("* ");
            }

            sb.Append("from ").Append(table);

            if (constrain != null)
            {
                sb.Append(" where ").Append(constrain);
            }

            control.DataSource = m_DBA.ExecuteDataSet(sb.ToString());
            control.DataBind();
        }
    }
}
